const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database().collection("user");

// 查询数据库集合云函数入口函数
exports.main = async (event, context) => {
  const status = event.status
  if(status != 1 && status != 2)
  {
    console.log(status)
    return {
      code:400,
      data:{},
      msg:"empty or wrong param"
    }
  }
  const sid = event.sid
  const wxContext = cloud.getWXContext()
  const result = await db.where({openid:wxContext.OPENID,status:0}).get()
  if(result.data.length == 0 )
  {
    return {
      code:401,
      data:{},
      msg:"no privilege"
    }
  }
  let admin = result.data[0]
  if(admin["status"])
  {
    return {
      code:401,
      data:{},
      msg:"no privilege"
    }
  }

  if(status == 1)
  {
    const update = await db.where({sid:sid}).update({data:{
      belong:admin.sid,
      status:1
    }})
    let updated = update.stats.updated
    if(updated == 0)
    {
        return {
          code:404,
          data:{
            updated:updated
          },
          msg:"not change"
        }
    }
    else
    {
      return {
        code:200,
        data:{
          updated:updated
        },
        msg:"success"
      }
    }
  }
  else
  {
    const update = await db.where({sid:sid,belong:admin.sid}).update({data:{
      belong:null,
      status:2
    }})
    let updated = update.stats.updated
    if(updated == 0)
    {
        return {
          code:404,
          data:{
            updated:updated
          },
          msg:"not change"
        }
    }
    else
    {
      return {
        code:200,
        data:{
          updated:updated
        },
        msg:"success"
      }
    }
  }
};
